<?php namespace simpleFlow\control;

use simpleFlow\Object as SFObject;
use simpleFlow\view\View as SFView;
use simpleFlow\Session as SFSession;
use simpleFlow\view\Theme as SFTheme;
use simpleFlow\request\RequestWeb as SFRequest;

/**
 * Control for classes
 */
class Control extends SFObject
{
	/**
	 * @var SFRequest
	 */
	public $objRequest;
	/**
	 * @var SFView
	 */
	public $objView;
	/**
	 * @var boolean If wants fetch mode to reutilize the code
	 */
	public $booFetchMode;
	
	/**
	 * Constructor
	 * @param SFView $objView View object
	 * @param boolean $booFetchMode If wants fetch mode
	 */
	public function __construct(SFView $objView = null,$booFetchMode = false)
	{
		$this->booFetchMode = $booFetchMode;
		if($objView)
		{
			$this->objView = $objView;
			$this->objView->sf_error_message = SFSession::getParam('sf_error_message',true);
			$this->objView->sf_success_message = SFSession::getParam('sf_success_message',true);
			$this->objView->sf_url = SF_URL_ROOT;
			if(!$booFetchMode) { $this->objView->objTheme = new SFTheme(SF_THEME,$this->objView); }
			
			$arrRequest = SFRequest::getRequest()->getParams();
			$arrConfig = SFSession::getParam('sf_config');
			
			$this->objView->addConfigDir(SF_APP_DIR_ROOT.'module'.DIRECTORY_SEPARATOR.''.$arrRequest['_module_'].DIRECTORY_SEPARATOR.'i18n'.DIRECTORY_SEPARATOR.$arrRequest['_app_'].DIRECTORY_SEPARATOR);
			//$this->objView->configLoad($arrConfig['app']['lang'].'.conf');
		}
	}
	
	/**
	 * Check the control permission
	 * @return boolean If have permission
	 */
	public function __checkPermission()
	{
		return SFSession::getParam('SF_USER_LOGGED') ? true : false;
	}
	
	/**
	 * Redirect to other URL
	 * @param string $strModule Module name
	 * @param string $strApp Application name
	 * @param string $strAction Action name
	 * @param array $arrParams Parameters
	 */
	public function redirect($strModule,$strApp,$strAction,$arrParams = array())
	{
		$strURL = SF_URL_ROOT."/{$strModule}/{$strApp}/{$strAction}";
		foreach($arrParams as $_strKey => $_strValue)
		{
			if(!\in_array($_strKey, array('_module_','_app_','_action_','_protocol_','_host_'))) { $strURL.= "/{$_strKey}/{$_strValue}"; }
		}
		header("location: {$strURL}");
	}
	
	/**
	 * Render the view
	 * @param string $strTemplate Template name
	 * @return string Html content if fetch mode is on
	 */
	public function renderView($strTemplate)
	{
		if($this->booFetchMode)
		{
			$arrClass = (\explode('\\', \get_class($this)));
			$_strTemplateDir = $this->objView->getTemplateDir();
			$this->objView->setTemplateDir(SF_APP_DIR_ROOT.'module'.DIRECTORY_SEPARATOR.$arrClass[3].DIRECTORY_SEPARATOR.'view'.DIRECTORY_SEPARATOR.$arrClass[5].DIRECTORY_SEPARATOR);
			$str = $this->objView->show($strTemplate);
			$this->objView->setTemplateDir($_strTemplateDir[0]);
			return $str;
		}else{
			$this->objView->show($strTemplate);
		}
	}
}

?>